<?php
namespace app\hotel\controller;

use app\common\controller\Hotel;
use app\common\library\util\Ems;
use app\common\library\util\Token;
use app\common\model\Business\Source;
use app\common\model\Business\Business as BusinessBusiness;
use app\common\model\Region;
use think\Request;
use fast\Random;
use Exception;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use think\Db;
use think\exception\ValidateException;
use think\exception\PDOException;

class Business extends Hotel
{
    protected $model = null;
    public function __construct(Request $request)
    {
        $this->model = new BusinessBusiness();
        $this->noLogin = ['login'];
        parent::__construct($request);
    }
    public function login()
    {
        $this->request->filter(['strip_tags', 'trim']);
        $mobile = $this->request->param('mobile','');
        $passwordInput = $this->request->param('password','');
        $business = $this->model->where('mobile',$mobile)->find();
        $result = [];
        if($business){
            $password = $business["password"];
            $salt = $business["salt"];
            if(md5(md5($passwordInput) . $salt)==$password){
                $token = Token::generateToken([
                    "id" => $business["id"],
                    "mobile" => $business["mobile"],
                ]);
                $data = [
                    'business'=>$business,
                    'token'=>$token,
                ];
                $this->success('登录成功','/business',$data);
            }else{
                $this->error('登录失败');
            }
        }else{
            $nickname = substr($mobile,0,3).'****'.substr($mobile,strlen($mobile)-4,strlen($mobile));
            $salt = Random::alnum(10);
            $password = md5(md5($passwordInput) . $salt);
            $sourceid = Source::whereLike('name','%酒店预订%')->find()['id'];
            $data = [
                'mobile' => $mobile,
                'nickname' => $nickname,
                'password' => $passwordInput,
                'salt' => $salt,
                'gender' => 0,
                'sourceid' => $sourceid,
                'deal' => 0,
                'money' => 0,
                'auth' => 0,
            ];
            $result = false;
            Db::startTrans();
            try {
                $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $this->validateFailException()->validate($data,$validate);
                $data['password'] = $password;
                $result = $this->model->create($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result === false) {
                $this->error('注册失败');
            }else{
                $token = Token::generateToken([
                    "id" => $result["id"],
                    "mobile" => $result["mobile"],
                ]);
                $data = [
                    'business'=>$business,
                    'token'=>$token,
                ];
                $this->success('注册成功','/business',$data);
            }
        }
    }
    public function Check()
    {
        $token = $this->request->param('token','');
        $result = parent::isLogin($token);
        $result['code']==0?$this->error($result['msg']):$this->success($result['msg'],null,$result['data']);
    }
    public function profile()
    {
        if(!$this->request->isPost())return ['code'=>0,'msg'=>'请求错误'];
        $this->request->filter(['strip_tags', 'trim']);
        $params = $this->request->post();
        if($this->model->where(['id'=>['<>',$this->business['id']],'mobile'=>$params['mobile']])->find())
        {
            $this->error('手机号已存在');
        }
        if($this->model->where(['id'=>['<>',$this->business['id']],'email'=>$params['email']])->find())
        {
            $this->error('邮箱已存在');
        }
        if($params['email']==$this->business['email']){
            unset($params['email']);
        }else{
            $params['auth'] = 0;
        }
        $code = isset($params['code'])?$params['code']:0;
        $region = Region::where('code',$code)->find();
        if($region){
            $parentpath = explode(',',$region['parentpath'].',,');
            $params['province'] = $parentpath[0];
            $params['city'] = $parentpath[1];
            $params['district'] = $parentpath[2];
        }
        $result = false;
        $preImgFile = '';
        $curImgFile = '';
        Db::startTrans();
        try {
            $ispassword = isset($params['password'])&&$params['password'];
            $ispassword||($params['password'] = '123456');
            $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
            $this->validateFailException()->validate($params,$validate);
            if(!$ispassword){
                unset($params['password']);
            }else{
                $params['salt'] = Random::alnum(10);
                $params['password'] = md5(md5($params['password']) . $params['salt']);
            }
            //上传图片
            $status = $this->upload();
            if($status['code']==1){
                $preImgFile = ROOT_PATH . 'public' . $this->business['avatar'];
                $curImgFile = ROOT_PATH . 'public' . $status['msg'];
                $params['avatar'] = $status['msg'];
            }else if($status['code']==2){
                throw new FileException($status['msg']);
            }
            $result = $this->business->allowField(true)->isUpdate(true)->save($params,['id'=>$this->business['id']]);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            if($curImgFile&&is_file($curImgFile)){
                unlink($curImgFile);
            }
            $this->error($e->getMessage());
        }
        if($preImgFile&&is_file($preImgFile)){
            unlink($preImgFile);
        }
        if ($result === false) {
            $this->error('修改失败');
        }
        $this->success('修改成功',null,$this->business);
    }
    public function upload()
    {
        $file = isset($_FILES['avatar'])?$_FILES['avatar']:null;
        $status = ['code'=>0];
        if(!$file){
            $status['msg'] = '';
            return $status;
        }
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->validate(['ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . '/' . 'uploads');
        if($info){
            $status['code'] = 1;
            $status['msg'] = '/' . 'uploads' . '/' . $info->getSaveName();
        }else{
            // 上传失败获取错误信息
            $status['code'] = 2;
            $status['msg'] = $file->getError();
        }
        return $status;
    }
    public function auth()
    {
        if($this->business['auth']){
            return $this->success('邮箱已认证,无需重复验证');
        }
        if($this->request->isGet()){
            $source = Source::where('id',$this->business['sourceid'])->find();
            if(!$source)return $this->error('平台出错');
            $status = Ems::send($this->business['email'],$source['name']);
            $this->result(null,$status['code'],$status['msg']);
        }
        $status = Ems::checkCode($this->business['email'],$this->request->post('vercode'));
        if($status['code']==1){
            $this->business['auth'] = 1;
            $this->business->save();
            return $this->success($status['msg']);
        }else{
            return $this->error($status['msg']);
        }
    }
}
